﻿using ProjectCloth.Entity;
using ProjectCloth.Entity.Enum;
using ProjectCloth.FrmUI.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{
    public partial class ReturnSaleOrderFrm : UserControl
    {
        private ClothContext db = new ClothContext();
        private List<Entity.Product> productList = new List<Entity.Product>();
        private int _size = 0;
        private string prefix = "J";
        private bool isSearch = false;
        private string _orderNo = "";
        private string _draftOrderNo = "";
        public ReturnSaleOrderFrm(string orderNo)
        {
            InitializeComponent();
            LoadSaleOrder(orderNo);
        }
        public void LoadSaleOrder(string orderNo)
        {

            littlecountTxt.Visible = false;
            littlecountlab.Visible = false;
            var order = db.SaleOrders.AsNoTracking().Where(o => o.OrderNo == orderNo).FirstOrDefault();
            if (order == null) return;

            isSearch = true;
            _orderNo = orderNo;
            if (order.OrderStatus == (int)OrderStatus.Pay)
            {
                payOrderBtn.Text = "保存修改";
                saveOrderBtn.Visible = false;
            }
            else if (order.OrderStatus == (int)OrderStatus.Unpay)
            {
                saveOrderBtn.Text = "未收修改";
                payOrderBtn.Text = "已收保存";
            }
            else if (order.OrderStatus == (int)OrderStatus.Checked)
            {
                saveOrderBtn.Visible = false;
                payOrderBtn.Visible = false;
            }
            //else if(order.OrderStatus == (int)OrderStatus.Checked) { }
            DataGridViewComboBoxColumn GenderColumn = Unit as DataGridViewComboBoxColumn;
            GenderColumn.Items.Add("米");
            GenderColumn.Items.Add("码");
            if (orderNo.Contains("D"))
            {
                prefix = "D";
                orderTypeLab.Text = "退货-大货单";
            }

            productList = db.Products.ToList();
            #region 表  头部/底部
            orderNoTxt.Text = order.OrderNo;
            makerCbx.DataSource = db.Users.Where(o => o.Enabled == true).ToList();
            makerCbx.DisplayMember = "Name";
            makerCbx.ValueMember = "Id";
            makerCbx.SelectedValue = order.MakerId;
            createTimePick.Value = order.CreateTime;
            inmoneyTime.Value = order.InMoneyDate;
            summaryTxt.Text = order.Summary;
            RemarkTxt.Text = order.Remark;
            customerTxt.Text = order.CustomerName;
            CompanyNameTxt.Text = order.CompanyName;
            LiaisonTxt.Text = order.Liaison;
            PhoneTxt.Text = order.Phone;
            inmoneycbb.DataSource = db.CashAccounts.ToList();
            inmoneycbb.DisplayMember = "TradeTypeName";
            inmoneycbb.ValueMember = "Id";
            if (order.InMoneyAccountId != null && order.InMoneyAccountId > 0)
                inmoneycbb.SelectedValue = order.InMoneyAccountId;
            else inmoneycbb.SelectedValue = 0;

            inmoneyAmountTxt.Text = order.InMoneyAmount.ToString();
            preferentialTxt.Text = order.Preferential.ToString();



            #endregion
            dataGridView1.Columns["ProductNo"].Visible = false;
            dataGridView1.Columns["ProductCode"].Visible = true;
            dataGridView1.Columns["ProductCode"].DisplayIndex = 0;
            dataGridView1.Columns["OrderItemStatus"].Visible = true;
            dataGridView1.Columns["OrderItemId"].Visible = false;
            var itemsSource = from o in db.SaleOrderItems.AsNoTracking().Where(o => o.OrderId == order.Id).ToList()
                              join p in db.Products.ToList() on o.ProductId equals p.Id
                              select new
                              {
                                  ProductCode = p.ProductNo,
                                  ProductName = p.Name,
                                  o.ColorType,
                                  Unit = EnumDefine.GetEnumDescription((Unit)o.Unit),
                                  o.Price,
                                  o.Quantity,
                                  Sum = o.Amount,
                                  o.Remark,
                                  OrderItemStatus = EnumDefine.GetEnumDescription((ItemStatus)o.OrderItemStatus),
                                  OrderItemId = o.Id
                              };
            dataGridView1.Refresh();
            dataGridView1.DataSource = itemsSource.ToList();

        }

        //改变键盘键enter效果
        #region
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            base.ProcessCmdKey(ref msg, keyData);
            var dgv = dataGridView1;
            TextBox salesum = (TextBox)this.Controls.Find("inmoneyAmountTxt", true)[0];
            bool _disable = false;

            switch (keyData)
            {
                case Keys.Enter:
                    if (dgv.CurrentRow != null)
                    {
                        if (dgv.CurrentRow.Cells["ProductNo"] != null && dgv.CurrentRow.Cells["ProductNo"].Value != null)
                        {

                            var productno = dgv.CurrentRow.Cells["ProductNo"].Value.ToString();
                            var product = productList.Where(p => p.ProductNo.Contains(productno)).FirstOrDefault();// productlist.Where(p => p.ProductId == productno).FirstOrDefault();
                            if (product != null)//&& sel)
                            {
                                if (dgv.CurrentRow.Cells["ProductName"].Value == null && dgv.CurrentRow.Cells["Price"].Value == null)
                                {
                                    //SendKeys.Send("{Tab}");
                                    //dgv.CurrentRow.Cells["ProductNo"].Value = product.ProductNo;
                                    //dgv.CurrentRow.Cells["ProductName"].Value = product.Name;
                                    //dgv.CurrentRow.Cells["ColorType"].Value = product.ColorType;
                                    dgv.CurrentRow.Cells["Price"].Value = _size == 0 ? product.Price : product.BatchPrice;
                                    //Unit.DefaultCellStyle.NullValue = _size == 0 ? "米" : "码";

                                }
                                dgv.CurrentRow.Cells["Sum"].Value =
                                         Convert.ToDecimal(dgv.CurrentRow.Cells["Price"].Value) * Convert.ToDecimal(dgv.CurrentRow.Cells["Quantity"].Value);//计算金额
                            }
                            if (dgv.CurrentRow.Cells["ColorType"].Selected == true)
                            {
                                SendKeys.Send("{Tab}");
                                //SendKeys.Send("{Tab}"); 
                            }
                            if (dgv.CurrentRow.Cells["Quantity"].Selected == true)
                            {
                                SendKeys.Send("{Tab}");
                            }
                            if (dgv.CurrentRow.Cells["Sum"].Selected == true)
                            {
                                decimal paysum = 0;
                                decimal quantity = 0;
                                for (int i = 0; i < dgv.RowCount - 1; i++)
                                {
                                    paysum += Convert.ToDecimal(dgv.Rows[i].Cells["Sum"].Value);
                                    quantity += Convert.ToDecimal(dgv.Rows[i].Cells["Quantity"].Value);
                                }
                                littlecountTxt.Text = quantity.ToString();
                                salesum.Text = paysum.ToString();
                            }
                        }
                        SendKeys.Send("{Tab}");
                    }
                    else
                    {
                        //if (summaryTxt.Focused == true)
                        if (LiaisonTxt.Focused == true)
                        {
                            dgv.Focus();
                        }


                    }

                    _disable = true;
                    break;
                case Keys.F12:
                    {
                        payOrderBtn_Click(null, null);
                        _disable = true;
                        break;
                    }
                case Keys.F10:
                    {
                        checkedBtn_Click(null, null);
                        _disable = true;
                        break;
                    }
                default:
                    break;
            }

            return _disable;
        }
        #endregion
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="status"></param>
        private void saveOrPayOrder(int status)
        {

            DataGridView dgv = dataGridView1;
            bool isAreadyPay = false;
            try
            {
                var result = 0;
                if (orderNoTxt.Text == "")
                {
                    return;
                }

                var order = new SaleOrder();
                if (isSearch)
                {
                    order = db.SaleOrders.AsNoTracking().Where(o => o.OrderNo == _orderNo).FirstOrDefault();
                    order = db.SaleOrders.Where(o => o.OrderNo == _orderNo).FirstOrDefault();
                    order.OutStore = "";
                    order.Name = "";
                    order.CustomerName = customerTxt.Text;
                    order.CreatorId = LoginInfo.GetLoginInfo().UserId;
                    order.CreatorName = LoginInfo.GetLoginInfo().UserName;
                    order.MakerId = Convert.ToInt32(makerCbx.SelectedValue);
                    order.MakerName = makerCbx.Text;
                    order.RecordDate = createTimePick.Value;// DateTime.Now;
                    order.InMoneyDate = inmoneyTime.Value;// DateTime.Now;
                    order.CreateTime = DateTime.Now;
                    order.Summary = summaryTxt.Text;
                    order.Remark = RemarkTxt.Text;
                    order.CompanyName = CompanyNameTxt.Text;
                    order.Liaison = LiaisonTxt.Text;
                    order.Phone = PhoneTxt.Text;
                    if (order.OrderStatus == 0)
                    {
                        order.DisClose = Convert.ToDecimal(preferentialTxt.Text == "" ? "0" : preferentialTxt.Text);
                        order.InMoneyAccountId = inmoneycbb.SelectedValue == null ? 0 : (int)inmoneycbb.SelectedValue;
                        order.OrderStatus = status;
                        order.InMoneyAmount = Convert.ToDecimal(inmoneyAmountTxt.Text == "" ? "0" : inmoneyAmountTxt.Text);
                        order.Preferential = Convert.ToDecimal(preferentialTxt.Text == "" ? "0" : preferentialTxt.Text);
                        order.FinalMoney = Convert.ToDecimal(finalMoneyTxt.Text == "" ? "0" : finalMoneyTxt.Text);
                    }
                    else
                    {
                        isAreadyPay = true;
                    }

                    //db.SaleOrders.Attach(order);
                    //db.Entry(order).State = System.Data.Entity.EntityState.Modified;
                    result = db.SaveChanges();

                }
                else
                {
                    order = new SaleOrder()
                    {
                        OrderNo = orderNoTxt.Text,
                        OutStore = "",
                        Name = "",
                        CustomerName = customerTxt.Text,
                        CreatorId = LoginInfo.GetLoginInfo().UserId,
                        CreatorName = LoginInfo.GetLoginInfo().UserName,
                        MakerId = Convert.ToInt32(makerCbx.SelectedValue),
                        MakerName = makerCbx.Text,
                        RecordDate = createTimePick.Value,// DateTime.Now,
                        InMoneyDate = inmoneyTime.Value,// DateTime.Now,
                        CreateTime = DateTime.Now,
                        Summary = summaryTxt.Text,
                        Remark = RemarkTxt.Text,
                        DisClose = Convert.ToDecimal(preferentialTxt.Text == "" ? "0" : preferentialTxt.Text),
                        InMoneyAccountId = status == 1 ? (inmoneycbb.SelectedValue == null ? 0 : (int)inmoneycbb.SelectedValue) : 0,
                        OrderStatus = status,
                        Status = 0,
                        InMoneyAmount = Convert.ToDecimal(inmoneyAmountTxt.Text == "" ? "0" : inmoneyAmountTxt.Text),
                        Preferential = Convert.ToDecimal(preferentialTxt.Text == "" ? "0" : preferentialTxt.Text),
                        FinalMoney = Convert.ToDecimal(finalMoneyTxt.Text == "" ? "0" : finalMoneyTxt.Text),
                    };
                    db.SaleOrders.Add(order);
                    result = db.SaveChanges();
                }

                if (result > 0) //
                {
                    var itemsResult = 0;
                    if (!isSearch)
                    {
                        List<SaleOrderItem> items = new List<SaleOrderItem>();
                        for (int i = 0; i < dgv.RowCount - 1; i++)
                        {
                            if (dgv.Rows[i].Cells["ProductNo"] != null && dgv.Rows[i].Cells["ProductNo"].Value != null)
                            {
                                //var dropDown = dgv.CurrentRow.Cells["ProductNo"];
                                //var productno = dropDown.EditedFormattedValue.ToString();
                                var productno = dgv.Rows[i].Cells["ProductNo"].Value.ToString();
                                var product = productList.Where(p => p.ProductNo.Contains(productno)).FirstOrDefault();
                                if (product == null)
                                {
                                    MessageBox.Show("未选择商品！");
                                    return;
                                }
                                if (product != null)//&& sel)
                                {
                                    SaleOrderItem sd = new SaleOrderItem()
                                    {
                                        OrderId = order.Id,
                                        ProductId = product.Id,//商品
                                        Quantity = Convert.ToDecimal(dgv.Rows[i].Cells["Quantity"].Value),//数量                                                                                       //Remark = dataGridView1.Rows[i].Cells[7].Value.ToString(),//备注
                                        Amount = Convert.ToDecimal(dgv.Rows[i].Cells["Sum"].Value),//估算总金额
                                        ColorType = dgv.Rows[i].Cells["ColorType"].Value == null ? "" : dgv.Rows[i].Cells["ColorType"].Value.ToString(),
                                        Unit = (int)(Enum.Parse(typeof(Entity.Enum.Unit), dgv.Rows[i].Cells["Unit"].EditedFormattedValue != null ? dgv.Rows[i].Cells["Unit"].EditedFormattedValue.ToString().Trim() : (_size == 0 ? "米" : "码"))),//单位
                                        Price = Convert.ToDecimal(dgv.Rows[i].Cells["Price"].Value),//价格
                                        Remark = dgv.Rows[i].Cells["remark"].Value == null ? "" : dgv.Rows[i].Cells["remark"].Value.ToString(),
                                        CreateDate = DateTime.Now,
                                        CreatorId = LoginInfo.GetLoginInfo().UserId,
                                        CreatorName = LoginInfo.GetLoginInfo().UserName,
                                        OrderNo = order.OrderNo,
                                        MakerId = Convert.ToInt32(makerCbx.SelectedValue)
                                    };
                                    items.Add(sd);
                                }
                            }

                        }
                        db.SaleOrderItems.AddRange(items);
                        itemsResult = db.SaveChanges();
                    }

                    //#region  修改流水记录 变更账户金额
                    //if ((itemsResult > 0 || isSearch) && status == 1 && !isAreadyPay)
                    //{
                    //    var cashAccount = db.CashAccounts.FirstOrDefault(o => o.Id == (int)inmoneycbb.SelectedValue);
                    //    if (cashAccount != null)
                    //    {
                    //        var orAmount = cashAccount.Amount;
                    //        var amount = order.FinalMoney;
                    //        cashAccount.OriginalAmount = orAmount;
                    //        cashAccount.Amount += amount;
                    //        cashAccount.UpdateTime = DateTime.Now;

                    //        var cashAccountLog = new CashAccountLog();
                    //        cashAccountLog.CurrentAmount = cashAccount.Amount;
                    //        cashAccountLog.OriginalAmount = orAmount;
                    //        cashAccountLog.CashAccountId = cashAccount.Id;
                    //        cashAccountLog.CreateTime = DateTime.Now;
                    //        cashAccountLog.LoginId = LoginInfo.GetLoginInfo().UserId;
                    //        cashAccountLog.MakerId = order.MakerId;
                    //        cashAccountLog.MakerTime = order.RecordDate;
                    //        cashAccountLog.RelatedObject = order.CustomerName;
                    //        cashAccountLog.Source = order.OrderNo;
                    //        cashAccountLog.Remark = order.Remark;
                    //        cashAccountLog.VariableAmount = order.FinalMoney;
                    //        cashAccountLog.CashAccountId = (int)inmoneycbb.SelectedValue;//建议直接读取id
                    //        db.CashAccountLogs.Add(cashAccountLog);
                    //        db.SaveChanges();
                    //    }

                    //}
                    //#endregion
                    var message = itemsResult > 0 ? "添加成功!" : "添加失败!";
                    if (isSearch)
                    {
                        message = result > 0 ? "修改成功!" : "修改失败!";
                    }
                    MessageBox.Show(message);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("添加失败!");
            }
            //更新草稿单字段，显示销售退货单单号
            if (!string.IsNullOrEmpty(_draftOrderNo))
            {
                var draftorder = db.DraftOrders.Where(o => o.OrderNo == _draftOrderNo).FirstOrDefault();
                if (draftorder != null && !string.IsNullOrEmpty(draftorder.OrderNo))
                {
                    draftorder.SaleOrderNo = orderNoTxt.Text;
                    db.SaveChanges();
                }
            }
            _draftOrderNo = "";
        }
        /// <summary>
        /// 保存订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveOrderBtn_Click(object sender, EventArgs e)
        {
            //if (inmoneycbb.SelectedValue != null && (int)inmoneycbb.SelectedValue > 0)
            //    saveOrPayOrder(1);
            //else
            saveOrPayOrder(0);
        }
        /// <summary>
        /// 保存已支付订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void payOrderBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(finalMoneyTxt.Text) || finalMoneyTxt.Text == "0" || finalMoneyTxt.Text == "0.00")
                {
                    MessageBox.Show("请检查金额！");
                    return;
                }
                if (inmoneycbb.SelectedValue == null)
                {
                    //MessageBox.Show("请选择收款账户！");
                    //return;
                    saveOrPayOrder(0);
                }
                else
                    saveOrPayOrder(1);
            }
            catch (Exception)
            {
                MessageBox.Show("输入错误！");
            }

        }
        /// <summary>
        /// 开始进货、修改进货
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {

                #region  开始进货、修改进货
                DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
                if (column is DataGridViewButtonColumn)
                {
                    var itemId = dataGridView1.CurrentRow.Cells["OrderItemId"].Value;
                    if (itemId != null && (int)itemId > 0)
                    {
                        var saleOrder = db.SaleOrders.Where(o => o.OrderNo == _orderNo).FirstOrDefault();
                        if (saleOrder == null || saleOrder.OrderStatus != (int)OrderStatus.Checked)
                        {
                            MessageBox.Show("请确认该销售退货单是否存在或者状态是否为已审核！");
                            return;
                        }
                        var main = MainFrm.CreateInstrance();
                        var tab = main.Controls.Find("tabControl1", true).FirstOrDefault() as TabControl;
                        var tabControl = tab;
                        if (tab != null)
                        {
                            tabControl = tab as TabControl;
                        }
                        dataGridView1.CurrentRow.Selected = true;
                        //new AddTab(new InStockFrm((int)itemId), "InStockFrm", "进货单", tabControl);
                        //new AddTab(new InStockItemFrm((int)itemId), "InStockFrm", "进货单", tabControl);
                        var instockfrm = new InStockItemFrm((int)itemId);
                        instockfrm.StartPosition = FormStartPosition.Manual;
                        instockfrm.Location = new Point(this.Right + 400 - instockfrm.Width, this.Bottom - instockfrm.Height);
                        instockfrm.ShowDialog();//或f.Show(this);或f.Show()
                        if (instockfrm.DialogResult == DialogResult.OK)
                        {
                            LoadSaleOrder(_orderNo);
                        }
                    }

                }
                #endregion
                //else if (e.RowIndex >= 0 && e.ColumnIndex == 0)
                //{
                //    var form = new ProductSelectFrm();
                //    var result = form.ShowDialog();
                //    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.productNo;
                //}
            }
        }
        /// <summary>
        /// 加载销售退货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void refreshBtn_Click(object sender, EventArgs e)
        {
            LoadSaleOrder(_orderNo);
        }

        private void inmoneyAmountTxt_TextChanged(object sender, EventArgs e)
        {
            changeFinal();
        }
        private void preferentialTxt_TextChanged(object sender, EventArgs e)
        {
            changeFinal();
        }
        /// <summary>
        /// 修改优惠后金额
        /// </summary>
        private void changeFinal()
        {
            try
            {
                if (string.IsNullOrEmpty(preferentialTxt.Text) || preferentialTxt.Text == "0" || preferentialTxt.Text == "0.00")
                {
                    finalMoneyTxt.Text = inmoneyAmountTxt.Text;
                }
                else
                {
                    if (string.IsNullOrEmpty(inmoneyAmountTxt.Text) || inmoneyAmountTxt.Text == "")
                    {
                        finalMoneyTxt.Text = "0";
                        preferentialTxt.Text = "0";
                    }
                    else
                    {
                        var amount = Convert.ToDecimal(inmoneyAmountTxt.Text) - Convert.ToDecimal(preferentialTxt.Text);
                        finalMoneyTxt.Text = amount.ToString();
                    }

                }
            }
            catch (Exception e)
            {
                MessageBox.Show("出现错误！，" + e.ToString());
            }
        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {
                var form = new ProductSelectFrm();
                var result = form.ShowDialog();
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.productNo;
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.CurrentRow.Cells["ColorType"].Selected == true && dataGridView1.CurrentRow.Cells["ColorType"].Value != null)
            {
                string txt = dataGridView1.CurrentRow.Cells["ColorType"].Value.ToString();
                dataGridView1.CurrentRow.Cells["ColorType"].Value = txt + "#";
            }
            if (dataGridView1.CurrentRow.Cells["Quantity"].Selected == true && dataGridView1.CurrentRow.Cells["Quantity"].Value != null)
            {
                dataGridView1.CurrentRow.Cells["Sum"].Value =
                                      Convert.ToDecimal(dataGridView1.CurrentRow.Cells["Price"].Value) * Convert.ToDecimal(dataGridView1.CurrentRow.Cells["Quantity"].Value);//计算金额
                decimal paysum = 0;
                decimal quantity = 0;
                for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                {
                    paysum += Convert.ToDecimal(dataGridView1.Rows[i].Cells["Sum"].Value);
                    quantity += Convert.ToDecimal(dataGridView1.Rows[i].Cells["Quantity"].Value);
                }
                littlecountTxt.Text = quantity.ToString();
                inmoneyAmountTxt.Text = paysum.ToString();
            }
        }
        private string GetOrderRemarkNo()
        {
            try
            {
                if (_size == 0)//剪版
                {
                    var text = db.SaleOrders.Where(o => o.OrderNo.Contains("J") && o.Status != (int)Status.Cancel).OrderByDescending(o => o.CreateTime).Select(o => o.Remark).FirstOrDefault();
                    if (text != null)
                    {
                        var list = text.Split('-');
                        if (list.Count() == 3 && list[2] != null)
                        {
                            int no = Convert.ToInt32(list[2]);
                            no += 1;
                            RemarkTxt.Text = list[0] + "-" + list[1] + "-" + no.ToString().PadLeft(4, '0');

                        }
                    }

                }
                else//大货
                {
                    var text = db.SaleOrders.Where(o => o.OrderNo.Contains("D") && o.Status != (int)Status.Cancel).OrderByDescending(o => o.CreateTime).Select(o => o.Remark).FirstOrDefault();
                    if (text != null)
                    {
                        var list = text.Split('-');
                        if (list.Count() == 3 && list[2] != null)
                        {
                            int no = Convert.ToInt32(list[2]);
                            no += 1;
                            RemarkTxt.Text = list[0] + "-" + list[1] + "-" + no.ToString().PadLeft(4, '0');
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("出现错误！");
            }
            return "";
        }

        private void preferentialTxt_Leave(object sender, EventArgs e)
        {
            changeFinal();
        }

        private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {


        }

        private void dataGridView1_MouseLeave(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 已审核销售退货单---退货单，金额为相反方向
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkedBtn_Click(object sender, EventArgs e)
        {
            var order = db.SaleOrders.AsNoTracking().Where(o => o.OrderNo == _orderNo).FirstOrDefault();
            #region  修改流水记录 变更账户金额
            if (order != null && order.OrderStatus == (int)OrderStatus.Pay)
            {
                var cashlog = db.CashAccountLogs.Where(o => o.Source == order.OrderNo && o.VariableAmount > 0).FirstOrDefault();

                var cashAccount = db.CashAccounts.FirstOrDefault(o => o.Id == (int)inmoneycbb.SelectedValue);
                if (cashAccount != null)
                {
                    order = db.SaleOrders.Where(o => o.OrderNo == _orderNo).FirstOrDefault();
                    order.OrderStatus = (int)OrderStatus.Checked;
                    if (cashlog == null || cashlog.VariableAmount <= 0)
                    {
                        var orAmount = cashAccount.Amount;
                        var amount = order.FinalMoney;
                        cashAccount.OriginalAmount = orAmount;
                        cashAccount.Amount += order.OrderNo.EndsWith("T") ? -amount : amount;//区分退货
                        cashAccount.UpdateTime = DateTime.Now;

                        var cashAccountLog = new CashAccountLog();
                        cashAccountLog.CurrentAmount = cashAccount.Amount;
                        cashAccountLog.OriginalAmount = orAmount;
                        cashAccountLog.CashAccountId = cashAccount.Id;
                        cashAccountLog.CreateTime = DateTime.Now;
                        cashAccountLog.LoginId = LoginInfo.GetLoginInfo().UserId;
                        cashAccountLog.MakerId = order.MakerId;
                        cashAccountLog.MakerTime = order.RecordDate;
                        cashAccountLog.RelatedObject = order.CustomerName;
                        cashAccountLog.Source = order.OrderNo;
                        cashAccountLog.Remark = order.Remark + (order.OrderNo.EndsWith("T") ? "退货单" : "");
                        cashAccountLog.VariableAmount = order.OrderNo.EndsWith("T") ? -order.FinalMoney : order.FinalMoney;
                        cashAccountLog.CashAccountId = (int)inmoneycbb.SelectedValue;//建议直接读取id
                        db.CashAccountLogs.Add(cashAccountLog);
                    }
                    var result = db.SaveChanges();
                    if (result > 0)
                    {
                        MessageBox.Show("审核成功！");
                    }
                }

            }
            else
            {
                MessageBox.Show("请确定该销售退货单是否存在或者状态是否为已支付！");
            }
            #endregion
        }
    }
}
